package com.lkd.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {


    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private VMService vmService;

    @Resource
    private UserService userService;

    @Resource
    private TaskDetailsService taskDetailsService;

    @Resource
    private MqttProducer mqttProducer;


    @Override
    @Transactional

    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }


    /**
     * 创建工单
     *
     * @param taskViewModel
     * @return
     */
    @Override
    @Transactional
    public boolean create(TaskViewModel taskViewModel) {

        //工单与机器状态校验
        checkCreateTask(taskViewModel.getInnerCode(), taskViewModel.getProductType());//验证售货机框架
        //查询同一台设备是否存在相同类型未完成工单
        if (hasTask(taskViewModel.getInnerCode(), taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }

        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());
        BeanUtils.copyProperties(taskViewModel, taskEntity);
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        taskEntity.setProductTypeId(taskViewModel.getProductType());

        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        taskEntity.setAddr(vmInfo.getNodeAddr());
        taskEntity.setRegionId(vmInfo.getRegionId());

        //跨服务调用用户信息
        UserVO userVO = userService.getUser(taskViewModel.getUserId());

        if (userVO == null) {
            throw new LogicException("维修人员不存在");
        }

        taskEntity.setUserName(userVO.getUserName());

        //查询执行人信息
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if (user == null) {
            throw new LogicException("任务执行人不存在");
        }
        taskEntity.setUserName(user.getUserName());

        this.save(taskEntity);

        //如果是补货工单，向工单明细表插入记录
        if (taskEntity.getTaskStatus().equals(VMSystem.TASK_TYPE_SUPPLY)) {
            taskViewModel.getDetails().forEach(d -> {
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(d, detailsEntity);
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }

        updateUserTaskCount(taskEntity, 1);


        return true;

    }

    /**
     * 更新用户工单数量
     *
     * @param taskEntity
     * @param offset
     */
    private void updateUserTaskCount(TaskEntity taskEntity, int offset) {
        String format = taskEntity.getCreateTime().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        String roleCode = "1002";
        Integer productTypeId = taskEntity.getProductTypeId();
        if (productTypeId != VMSystem.TASK_TYPE_SUPPLY) {
            roleCode = "1003";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF + format + "." + taskEntity.getRegionId() + "." + roleCode;

        redisTemplate.opsForZSet().incrementScore(key, taskEntity.getUserId(), offset);

    }


    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyMMdd"));
        String key = "lkd.date.code" + date;
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }

        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }

    /*public static void main(String[] args) {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyMMdd"));
        System.out.println("date = " + date);
        String key = "lkd.date.code." + date;
        System.out.println("key = " + key);

        String s = Strings.padStart(date, 9, 'a');
        System.out.println("s = " + s);
    }*/

    /**
     * 创建工单校验
     *
     * @param innerCode   设备编号
     * @param productType 工单类型
     * @throws LogicException
     */
    private void checkCreateTask(String innerCode, int productType) throws LogicException {
        //根据设备编号查询设备
        VmVO vmInfo = vmService.getVMInfo(innerCode);
        if (vmInfo == null) throw new LogicException("设备校验失败");
        //如果是投放工单，状态为营运
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备已在运营");
        }
        //如果是补货工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }
        //如果是撤机工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_REVOKE && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }

    }

    /**
     * 判断同一台设备是否存在未完成工单
     *
     * @param innerCode
     * @param productType
     * @return
     */
    private boolean hasTask(String innerCode, int productType) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda().select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productType)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        return this.count(qw) > 0;
    }

    /**
     * 获取工单详情
     *
     * @param taskId
     * @return
     */
    @Override
    public TaskEntity taskInfo(Long taskId) {
        TaskEntity taskEntity = getById(taskId);
        if (taskEntity == null) {
            throw new LogicException("工单数据不存在");
        }
        return taskEntity;
    }

    /**
     * 接受工单
     *
     * @param id
     * @return
     */
    @Override
    public Boolean accept(Long id) {
        TaskEntity taskEntity = this.getById(id);
        if (taskEntity.getTaskStatus() != VMSystem.TASK_STATUS_CREATE) {
            throw new LogicException("该工单不是待处理状态");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);

        return this.updateById(taskEntity);
    }

    /**
     * 取消工单
     *
     * @param id
     * @param viewModel
     * @return
     */
    @Override
    public Boolean cancelTask(Long id, CancelTaskViewModel viewModel) {

        TaskEntity taskEntity = this.getById(id);
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("工单已结束");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        taskEntity.setDesc(viewModel.getDesc());

        updateUserTaskCount(taskEntity, -1);

        return this.updateById(taskEntity);
    }

    /**
     * 完成工单
     *
     * @param id
     * @return
     */
    @Override
    public Boolean completeTask(Long id) {
        TaskEntity taskEntity = this.getById(id);
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("工单已结束");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);

        this.updateById(taskEntity);

        //如果是运维工单向售货机发消息
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_DEPLOY || taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_REVOKE) {
            sendMsgToVmsStasus(taskEntity);
        }
        ;

        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            //补货工单发送消息
            sendMsgtoVmsSupply(taskEntity);
        }


        return true;
    }

    /**
     * 补货工单发送消息
     *
     * @param taskEntity
     */
    private void sendMsgtoVmsSupply(TaskEntity taskEntity) {
        //根据id查询工单详情表
        QueryWrapper<TaskDetailsEntity> qw = new QueryWrapper<>();
        qw.lambda().eq(TaskDetailsEntity::getTaskId, taskEntity.getTaskId());
        List<TaskDetailsEntity> list = taskDetailsService.list(qw);

        //封装补货数据
        SupplyContract supplyContract = new SupplyContract();
        //设置售货机编号
        supplyContract.setInnerCode(taskEntity.getInnerCode());

        //补货货到数据
        List<SupplyChannel> supplyContractList = new ArrayList<>();

        //将补货明细添加到补货数据中
        list.forEach(d -> {
            SupplyChannel channel = new SupplyChannel();
            channel.setChannelId(d.getChannelCode());
            channel.setCapacity(d.getExpectCapacity());
            supplyContractList.add(channel);
        });

        supplyContract.setSupplyData(supplyContractList);
        //发送消息到售货机微服务
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 2, supplyContract);
        } catch (Exception e) {
            throw new LogicException("发送补货工单协议消息出错");
        }

    }

    /**
     * 向售货机微服务发送消息
     *
     * @param taskEntity
     */
    private void sendMsgToVmsStasus(TaskEntity taskEntity) {
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();

        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, taskCompleteContract);
        } catch (Exception e) {
            throw new LogicException("发送完成运维工单协议消息出错");
        }

    }


    /**
     * 查询指定时间范围内的工单列表
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public List<TaskEntity> getUserTask(DateTime begin, DateTime end) {

        LambdaQueryWrapper<TaskEntity> wrapper = Wrappers.<TaskEntity>lambdaQuery()
                .between(TaskEntity::getCreateTime, begin, end)
                .ne(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_CANCEL)
                .eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_REPAIR);


        return list(wrapper);
    }
}
